<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace support\exception;

use app\service\WechatQyService;
use support\Cache;
use support\Log;
use Webman\Http\Request;
use Webman\Http\Response;
use Throwable;
use Webman\Exception\ExceptionHandler;

/**
 * Class Handler
 * @package support\exception
 */
class Handler extends ExceptionHandler
{
    public $dontReport = [
        BusinessException::class,
    ];

    public function report(Throwable $exception)
    {
        $code          = $exception->getCode();
        $file          = $exception->getFile();
        $line          = $exception->getLine();
        $env           = ENVIRONMENT == 'PRO' ? '正式环境' : '测试环境';
        $request       = \request();
        $url           = ($request->getRemotePort() == 443 ? 'https:' : 'http:') . $request->fullUrl();
        $ip            = $request->getRealIp();
        $message       = $exception->getMessage();
        $errorMessage = "[{$env}]转换项目\n访问地址: {$url}\n[{$code}]\nIP地址: {$ip}\n错误信息: ErrorException in\n   {$file}\n   line {$line}\n   {$message}";
        Log::channel('debug')->debug($exception->getTraceAsString());
        if (ENVIRONMENT == 'PRO') {
            $log_key = __METHOD__ . '-' . md5($code . $line . $file) . "-server-error";
            $send    = Cache::get($log_key);
            if (!$send) {
                WechatQyService::instance()->textSend($errorMessage);
                Cache::set($log_key, 1, 3 * 60);
            }
        }
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception): Response
    {
        if ($this->_debug) {
            return parent::render($request, $exception);
        } else {
            return view('public/500');
        }
    }
}